<?php
// $Id $

/**
 * @file
 * Commonly functions used in heartbeat
 */

/**
 * Include heartbeat .inc class files
 */
function heartbeat_include($file, $module = 'heartbeat', $_file_path = '') {

  static $loaded = array();
  $file = strtolower($file);
  $path = drupal_get_path('module', $module);
  $_file_path = empty($_file_path) ? $file . '.inc' : $_file_path;

  if (!isset($loaded[$file])){

    $file_path = $path . '/includes/'. $_file_path;
    if (is_file($file_path)) {
      require $file_path;
      $loaded[$file] = TRUE;
    }
    $file_path = $path . '/'. $_file_path;
    if (is_file($file_path)) {
      require $file_path;
      $loaded[$file] = TRUE;
    }
  }


  return $loaded[$file];

}

/**
 * Decode heartbeat message variables
 */
function heartbeat_decode_message_variables($string, $object = false) {
  // Variable string need to be cleared from spaces to decode properly
  $array = explode("-|-", $string);
  $variables = array();
  if (!empty($array)) {
    foreach($array as $varvalue) {
      $parts = explode("=|=", $varvalue);
      if (isset($parts[0]) && !empty($parts[0])) {
        if (eregi("\*\*\*", $parts[1])) {
          $parts[1] = explode("***", $parts[1]);
        }
        $variables[$parts[0]] = !is_array($parts[1]) ? (string)$parts[1] : $parts[1];
      }
    }
  }
  //$variables = unserialize($string);
  return $object ? (object) $variables : (array) $variables;
}

/**
 * Encode heartbeat message variables
 */
function heartbeat_encode_message_variables($array) {
  $string = '';
  foreach($array as $key => $value) {
    if (is_array($value)) {
      $value = implode('***', $value);
    }
    $string .= $key.'=|=' . $value . '-|-';
  }
  //$string = serialize((object)$array);
  return $string;
}

/**
 * compares variables that need to be included
 *   with variables that are already there and
 *   check their values to fit as default value
 *   in a textarea
 *
 * @param array $settings
 * @param array $form_settings
 * @param string $variables
 * @return string fit for textarea
 */
function heartbeat_variables_compare($variables = array(), $defaults = array(), $flipped = true) {

  $default_values = '';

  // normal settings from rules action, rules cache
  $vars = array();
  if (isset($defaults)) {
    $vars = heartbeat_decode_message_variables($defaults, false);
  }

  if($flipped) {
    $variables = array_flip($variables);
  }

  // See if there is already a token assignment on a variable
  foreach($variables as $variable_word => $key) {
    // Standardize possible variable formats
    $variable_normal = !eregi("@",$variable_word) ? "@".$variable_word : $variable_word;
    $variable_part = !eregi("#",$variable_word) ? "#".$variable_word : $variable_word;
    if(!empty($vars[$variable_normal])) {
      $default_values .= $variable_normal."=".$vars[$variable_normal]."\r\n";
    }
    elseif(!empty($vars[$variable_part])) {
      $default_values .= $variable_part."=".$vars[$variable_part]."\r\n";
    }
    elseif(!empty($vars[$variable_word])) {
      $default_values .= $variable_normal."=".$vars[$variable_word]."\r\n";
    }
    else {
      $default_values .= $variable_normal."=\r\n";
    }
  }
  return $default_values;
}

/**
 * Function looks for variables in an array of given strings
 * @return array of words and variables found (separately stored)
 * @remark
 *   %targetnames% do not have to be tokenized
 */
function heartbeat_match_variables() {

  $args = func_get_args();
  $string ='';
  $string .= implode(' ', array_values($args));

  preg_match_all("/\!([a-zA-Z0-9_]+)/",$string, $matches);
  $words = $matches[1];
  $variables = $matches[0];
  $found = array('words' => $words,'variables' => $variables);

  return $found;
}

/**
 * Helper function to map a array to dropdown
 *   with a field and value for the options
 *
 * @param array $options
 * @param string target $field
 * @param sring target $value
 * @return array mapped for options dropdown
 */
function _heartbeat_map_assoc($options, $field, $value) {
  $mapped = array();
  foreach($options as $heartbeat_activity) {
    $mapped[$heartbeat_activity->{$field}] = $heartbeat_activity->{$value};
  }
  return $mapped;
}

/**
 * Helper function to get the fields
 */
function _heartbeat_get_fields($table) {
  $fields = array();
  $schema = drupal_get_schema($table, true);
  // Go through our schema
  foreach ($schema['fields'] as $field => $info) {
    $fields[$field] = !empty($info['alias']) ? $info['alias'] : $field;
  }
  return $fields;
}

/**
 * Helper function to check if a user has access to edit/delete buttons
 */
function _heartbeat_activity_stream_delete_access() {
  if (variable_get('heartbeat_activity_stream_delete', 1)) {
    return user_access('delete heartbeat activity logs');
  }
  return FALSE;
}

/**
 * Helper function to check if a user has access to delete a message
 */
function _heartbeat_message_delete_access($uaid) {
  if (_heartbeat_activity_stream_delete_access()) {
    return TRUE;
  }

  if (variable_get('heartbeat_activity_stream_actor_delete',1)) {
    global $user;
    $uid = db_result(db_query("SELECT uid FROM {heartbeat_activity} WHERE uaid = %d", $uaid));
    return $uid == $user->uid;
  }
  return FALSE;
}

/**
 * Helper function to get the options for access types
 *
 * @return array of access types
 */
function _heartbeat_access_type_options() {
  $return = array();
  $types = variable_get('heartbeat_access_types', array());
  foreach ($types as $type) {
    $return[$type['class']] = $type['name'];
  }
  return $return;
}

/**
 * Helper function to fetch the defined variables for this message
 */
function heartbeat_rule_action_get_variables($message_id, $values = array()) {

  if($message_id) {
    // With the message id, we fetch the whole message
    $message = heartbeat_message_load($message_id, 'message_id');
    $defined_variables = heartbeat_match_variables($message->message, $message->message_concat);

    // If words are found as match to a heartbeat message variable,
    // variables are needed in the message
    if(count($defined_variables['words']) > 0) {

      // Add the textarea where all the magic variables go into
      return heartbeat_variables_compare($defined_variables['words'], $values);
    }
  }

  return '';
}

/**
 * Function to get the allowed tags for heartbeat strings
 */
function heartbeat_allowed_tags() {
  $tags = str_replace(' ', '', variable_get('heartbeat_allowed_tags', ''));
  return explode(',', $tags);
}

/**
 *
 * @return unknown_type
 */
function _theme_time_ago($time) {

  return format_interval(($_SERVER['REQUEST_TIME'] - $time), 1) .' '. t('ago') ;
}